﻿Imports ADOConnection

Public Class frmPhieuNXDCSS

#Region "Paramaters"
    Public fViewPhieuNX As frmViewPhieuNX = Nothing
    Public objPhieu As CPhieuNX
    Public enumNX As enumDOITUONG 'De xac dinh phieu nhap, phieu xuat

    'Chi dung cho cmbLK(cmbLoaiMH) 
    'de kiem tra neu chon Loai Kho( Loai Thuoc) khac se mat du lieu mat hang
    Private objLK As CDoiTuong
    Private objLoaiMH As CLoaiThuoc

    'Cac bien dung de truy xuat du lieu in DatagridView
    Private sdaSLNX As IDbDataAdapter
    Private dsDataSet As DataSet

    'Bien luu slton dau ky theo so sach va theo kiem ke
    Public slss11 As Double = 0
    Public slkk11 As Double = 0

    Private RowCount As Integer = 0 'De xu ly SoKH khi them mathang moi 


    Public Enum enumLabelNotify
        None = -1
        DOITUONG = 0
        MaColumn = 2
        HSDColumn = 3
        SLKHColumn = 4
        SLTHColumn = 5
    End Enum
#End Region

#Region "Events"

#Region "General"
    Private Sub frmPhieuNhap_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Lay danh sach Loai Kho
        Dim arys As ArrayList = CDoiTuongs.GetDoiTuongList(enumDOITUONG.LOAIKHO)
        cmbLK.DisplayMember = "Ten"
        cmbLK.ValueMember = "KH"
        cmbLK.DataSource = arys

        'Lay danh sach Loai Thuoc
        arys = CLoaiThuocs.GetLoaiThuocListByMaCha(CLoaiThuocs.GetLoaiThuocByTen("Kho 706").MaLoaiThuoc)
        cmbLoaiMH.DisplayMember = "TenLoaiThuoc"
        cmbLoaiMH.ValueMember = "MaLoaiThuoc"
        cmbLoaiMH.DataSource = arys

        If g_User.Ban_ID = enumPHANQUYEN.TCT Then
            'chkTCXacNhan.Visible = True
            btnXoa.Visible = False
            btnCapnhatNew.Visible = False
            btnInPhieu.Visible = False
            'Else
            'chkTCXacNhan.Visible = False
        End If
        lblNotify.Text = ""
        Init()
    End Sub

    Private Sub cmbLK_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLK.Enter
        objLK = cmbLK.SelectedItem
    End Sub

    Private Sub cmbLK_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLK.SelectedIndexChanged
        lblLK_ID.Text = CType(sender.SelectedItem, CDoiTuong).KH
        Try
            If objLK.Ten <> CType(sender.SelectedItem, CDoiTuong).Ten Then
                If gridCTPhieu.RowCount > 0 Then
                    If MessageBox.Show("Chọn Loại kho khác sẽ mất các Mặt Hàng đang có.Bạn có chắc chọn không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) = Windows.Forms.DialogResult.Yes Then
                        dsDataSet.Tables(0).Clear()
                        gridCTPhieu.DataSource = dsDataSet.Tables(0).DefaultView
                    Else
                        'Quay tro lai neu ko chon cai khac
                        cmbLK.SelectedValue = objLK.KH
                        lblLK_ID.Text = objLK.KH
                    End If
                End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub cmbLoaiMH_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLoaiMH.Enter
        objLoaiMH = cmbLoaiMH.SelectedItem
    End Sub

    'Private Sub cmbLoaiMH_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLoaiMH.SelectedIndexChanged
    '    Try
    '        If objLoaiMH.TenLoaiThuoc <> CType(sender.SelectedItem, CLoaiThuoc).TenLoaiThuoc Then
    '            If gridCTPhieu.RowCount > 0 Then
    '                If MessageBox.Show("Chọn Loại Mặt Hàng khác sẽ mất các Mặt Hàng đang có.Bạn có chắc chọn không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) = Windows.Forms.DialogResult.Yes Then
    '                    dsDataSet.Tables(0).Clear()
    '                    gridCTPhieu.DataSource = dsDataSet.Tables(0).DefaultView
    '                Else
    '                    'Quay tro lai truoc khi chon
    '                    cmbLoaiMH.SelectedValue = objLoaiMH.MaLoaiThuoc
    '                End If
    '            End If
    '        End If
    '    Catch ex As Exception

    '    End Try
    'End Sub
#End Region

#Region "gridCTPhieu"
    Private Sub gridCTPhieu_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles gridCTPhieu.CellBeginEdit
        If e.ColumnIndex = gridCTPhieu.Columns("slkh").Index Then
            gridCTPhieu.Columns("slkh").DefaultCellStyle.Format = Nothing
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("slth").Index Then
            gridCTPhieu.Columns("slth").DefaultCellStyle.Format = Nothing
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("gle").Index Then
            gridCTPhieu.Columns("gle").DefaultCellStyle.Format = Nothing
        End If
    End Sub

    Private Sub gridCTPhieu_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridCTPhieu.CellDoubleClick
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            If enumNX = enumDOITUONG.TINHCHATNHAP Then
                If gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("ma").Index _
                And gridCTPhieu.Rows(gridCTPhieu.SelectedCells(0).RowIndex).Cells("ma").Value Is DBNull.Value Then
                    If gridCTPhieu.SelectedCells(0).RowIndex < RowCount Then
                        Dim frm As New frmVatTu(CType(cmbLoaiMH.SelectedItem, CLoaiThuoc).MaLoaiThuoc)
                        frm.fCallPhieuNX = Me
                        frm.ShowDialog(Me)
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub gridCTPhieu_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gridCTPhieu.Enter
        RowCount = GetRowCount()
        ShowSoKH_TGiaTri()
    End Sub

    Private Sub gridCTPhieu_CellEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridCTPhieu.CellEnter
        lblSLTON.Text = ""
        lblNotify.Text = ""
        If e.ColumnIndex = gridCTPhieu.Columns("slkh").Index And g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            Try
                slkk11 = gridCTPhieu.Rows(e.RowIndex).Cells("slkk11").Value
            Catch ex As Exception
                slkk11 = 0
            End Try
            If objPhieu Is Nothing Then
                Try
                    slss11 = gridCTPhieu.Rows(e.RowIndex).Cells("slss11").Value
                Catch ex As Exception
                    slss11 = 0
                End Try
            Else
                Try
                    If objPhieu.NX = "N" Then
                        slss11 = gridCTPhieu.Rows(e.RowIndex).Cells("slss11").Value - gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value
                    Else
                        slss11 = gridCTPhieu.Rows(e.RowIndex).Cells("slss11").Value + gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value
                    End If
                Catch ex As Exception
                    slss11 = 0
                End Try
            End If
            If slss11 > 0 Then
                If slkk11 > 0 Then
                    lblSLTON.Text = "Số lượng tồn đầu kỳ sổ sách = " + slss11.ToString(FormatQuantityStyle()) + ". Số lượng kiểm kê = " + slkk11.ToString(FormatQuantityStyle())
                Else
                    lblSLTON.Text = "Số lượng tồn đầu kỳ sổ sách = " + slss11.ToString(FormatQuantityStyle()) + ". Số lượng kiểm kê = 0"
                End If
            Else
                If slkk11 > 0 Then
                    lblSLTON.Text = "Số lượng tồn đầu kỳ sổ sách = 0. Số lượng kiểm kê = " + slkk11.ToString(FormatQuantityStyle())
                Else
                    lblSLTON.Text = "Số lượng tồn đầu kỳ sổ sách = 0. Số lượng kiểm kê = 0"
                End If
            End If
        Else
            lblNotify.Text = GetLabelNotify()
        End If
    End Sub

    'Thuc hien khi cap nhat slkh hay slth
    Private Sub gridCTPhieu_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridCTPhieu.CellEndEdit
        If e.ColumnIndex = gridCTPhieu.Columns("slkh").Index _
        Or e.ColumnIndex = gridCTPhieu.Columns("slth").Index _
        Or e.ColumnIndex = gridCTPhieu.Columns("gle").Index Then
            gridCTPhieu.Columns("slkh").DefaultCellStyle.Format = FormatQuantityStyle()
            gridCTPhieu.Columns("slth").DefaultCellStyle.Format = FormatQuantityStyle()
            gridCTPhieu.Columns("gle").DefaultCellStyle.Format = FormatMoneyStyle()
            Dim slkh As Double = 0
            Dim slth As Double = 0
            Dim gle As Double = 0
            If gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value IsNot DBNull.Value Then
                If gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value < 0 Then
                    ShowMessages("Số lượng kế hoạch phải > 0")
                    gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value = DBNull.Value
                    Exit Sub
                End If
            End If

            If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
                'Lay slkh
                Try
                    slkh = gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value
                Catch ex As Exception
                    slkh = 0
                End Try
                'Lay slth
                gridCTPhieu.Rows(e.RowIndex).Cells("slth").Value = slkh
                slth = slkh
            ElseIf g_User.Ban_ID = enumPHANQUYEN.TCT Then
                'Lay slth
                Try
                    slth = gridCTPhieu.Rows(e.RowIndex).Cells("slth").Value
                Catch ex As Exception
                    slth = 0
                End Try
                'Lay slkh
                gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value = slth
                slkh = slth
            End If

            Try
                gle = gridCTPhieu.Rows(e.RowIndex).Cells("gle").Value
            Catch ex As Exception
                gle = 0
            End Try

            '***Phai doi ra dung format truoc khi tinh thanh tien
            If slkh > 0 Then
                slkh = CType(slkh.ToString(FormatMoneyStyle()), Double)
            End If
            If gle > 0 Then
                gle = CType(gle.ToString(FormatMoneyStyle()), Double)
            End If

            'Tinh thanh tien sau khi format xong
            Dim thanhtien As Double = slkh * gle
            thanhtien = CType(thanhtien, Long)
            gridCTPhieu.Rows(e.RowIndex).Cells("thanhtien").Value = thanhtien
            ShowSoKH_TGiaTri()
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("makho").Index Then
            If cmbLoaiMH.SelectedIndex < 0 Then
                ShowMessages("Phải chọn Loại Mặt Hàng trước mới có thể thêm mặt hàng")
                Exit Sub
            End If

            If cmbLK.SelectedIndex < 0 Then
                ShowMessages("Phải chọn nhập vào Loại Kho trước mới có thể thêm mặt hàng")
                Exit Sub
            End If

            If gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value Is DBNull.Value Then
                ShowMessages("Phải chọn Kho chứa mặt hàng trước.")
                Exit Sub
            End If

            Dim frm As frmLoHang
            If objPhieu IsNot Nothing Then
                frm = New frmLoHang(objPhieu.DPNX_ID, objPhieu.NGAY, cmbLK.SelectedValue.ToString(), gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value.ToString())
            Else
                frm = New frmLoHang(cmbLK.SelectedValue.ToString(), gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value.ToString())
            End If

            frm.fCallPhieuNX = Me
            frm.ShowDialog(Me)
            'End If
            RowCount = GetRowCount()
        End If
    End Sub

    Private Sub gridCTPhieu_UserDeletedRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) Handles gridCTPhieu.UserDeletedRow
        RowCount = GetRowCount()
        ShowSoKH_TGiaTri()
    End Sub

    Private Sub gridCTPhieu_UserAddedRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) Handles gridCTPhieu.UserAddedRow
        RowCount = GetRowCount()
        For count As Integer = 0 To RowCount - 1
            gridCTPhieu.Rows(count).HeaderCell.Value = (count + 1).ToString
        Next
        txtSoKH.Text = RowCount.ToString
    End Sub
#End Region

#Region "Textbox"
    'To mau cho control khi Focus
    Private Sub textBox_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles txtSoPhieu.Enter, txtNgayPH.Enter, dtNgay.Enter, txtNguoiVP.Enter, txtSoKH.Enter, txtTrLuong.Enter, txtSoKien.Enter, txtTGiaTri.Enter, txtNguoiGN.Enter, txtNgayGN.Enter
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            Try
                SetColorAllControls(sender, True)
                If (CType(sender, TextBox) Is txtDVGN) Or (CType(sender, TextBox) Is txtTCNX) Then
                    If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
                        lblNotify.Text = GetLabelNotify(enumLabelNotify.DOITUONG)
                    End If
                End If
                If (sender Is txtSoKH) Or (sender Is txtSoKien) Or (sender Is txtTrLuong) Then
                    Dim txt As TextBox = CType(sender, TextBox)
                    txt.Text = CInt(txt.Text).ToString()
                End If
            Catch ex As Exception

            End Try
        End If
    End Sub

    Private Sub textBox_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles txtNgayPH.Leave, dtNgay.Leave, txtNguoiVP.Leave, txtSoKH.Leave, txtTrLuong.Leave, txtSoKien.Leave, txtTGiaTri.Leave, txtNguoiGN.Leave, txtNgayGN.Leave, txtDVGN.Leave, txtTCNX.Leave
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            SetColorAllControls(sender, False)
            lblNotify.Text = GetLabelNotify()
            If (sender Is txtSoKH) Or (sender Is txtSoKien) Or (sender Is txtTrLuong) Then
                Dim txt As TextBox = CType(sender, TextBox)
                Try
                    txt.Text = Format(CInt(txt.Text), FormatQuantityStyle())
                Catch ex As Exception
                    txt.Text = 0
                End Try
            End If
        End If
    End Sub

    Private Sub txtSoPhieu_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSoPhieu.KeyPress, txtNguoiVP.KeyPress, txtNguoiGN.KeyPress
        If sender Is txtSoPhieu Then
            e.KeyChar = Char.Parse(StrConv(e.KeyChar.ToString, VbStrConv.Uppercase))
        Else
            If CType(sender, TextBox).Text.Length = 0 Then
                e.KeyChar = Char.Parse(StrConv(e.KeyChar.ToString, VbStrConv.ProperCase))
            End If
        End If
    End Sub

    ''' <summary>
    ''' Update: 25-01-2010
    ''' Kiểm tra số phiếu có bị trùng không
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtSoPhieu_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSoPhieu.Leave
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            SetColorAllControls(sender, False)
            lblNotify.Text = GetLabelNotify()
            'Kiem tra phieu nay da ton tai chua
            Dim sophieu As String = txtSoPhieu.Text.Trim()
            If objPhieu Is Nothing Then
                If CPhieuNXs.IsExist(enumNX, sophieu) Then
                    ShowMessages("Số phiếu này bị trùng.")
                    txtSoPhieu.Focus()
                End If
            Else
                If CPhieuNXs.IsExist(enumNX, sophieu, objPhieu.DPNX_ID) Then
                    ShowMessages("Số phiếu này bị trùng.")
                    txtSoPhieu.Focus()
                End If
            End If
        End If
    End Sub

    Private Sub txtNgayGN_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtNgayGN.Leave
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            If Not KiemTraNgayHopLe(txtNgayGN.Text) Then
                ShowError("Ngày không hợp lệ")
                txtNgayGN.Focus()
            End If
        End If
    End Sub

    Private Sub txtNgayPH_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtNgayPH.Leave
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            If Not KiemTraNgayHopLe(txtNgayPH.Text) Then
                ShowError("Ngày không hợp lệ.")
                txtNgayPH.Focus()
            End If
        End If
    End Sub

    Private Sub txtDoiTuong_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDVGN.DoubleClick
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            ShowFormDoiTuong(enumDOITUONG.DONVI, txtDVGN.Text)
        End If
    End Sub

    Private Sub txtDoiTuong_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtDVGN.KeyDown
        If e.KeyCode = Keys.F1 Then
            txtDoiTuong_DoubleClick(sender, Nothing)
        End If
    End Sub

    Private Sub txtDoiTuong_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDVGN.Leave
        SetColorAllControls(sender, False)
        lblNotify.Text = GetLabelNotify()

        Dim loai As enumDOITUONG
        loai = enumDOITUONG.DONVI
        Dim strTen As String = CType(sender, TextBox).Text

        If strTen <> "" Then
            Dim arrFind As ArrayList = CDoiTuongs.SearchDoiTuong(loai, strTen)
            If arrFind.Count = 0 Then
                ShowFormDoiTuong(loai, strTen)
            ElseIf arrFind.Count = 1 Then
                Dim objDoiTuong As CDoiTuong = CType(arrFind(0), CDoiTuong)
                lblDVGN_ID.Text = objDoiTuong.KH
                txtDVGN.Text = objDoiTuong.Ten
            End If
        Else 'Neu strTen = "" thi xoa ID trong label
            lblDVGN_ID.Text = ""
        End If
    End Sub
#End Region

#Region "Button"
    Private Sub btnCapNhat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhat.Click, btnCapnhatNew.Click
        Try
            If cmbLoaiMH.SelectedIndex < 0 Then
                ShowMessages("Chưa chọn Loại mặt hàng")
                If cmbLoaiMH.CanFocus Then
                    cmbLoaiMH.Focus()
                End If
                Exit Sub
            End If

            If txtSoPhieu.Text = "" Then
                ShowMessages("Số Phiếu chưa nhập")
                If txtSoPhieu.CanFocus Then
                    txtSoPhieu.Focus()
                End If
                Exit Sub
            End If

            If lblDVGN_ID.Text = "" Then
                ShowMessages("Đơn vị giao nhận chưa chọn")
                If txtDVGN.CanFocus Then
                    txtDVGN.Focus()
                End If
                Exit Sub
            End If

            If gridCTPhieu.RowCount = 0 Then
                ShowMessages("Chưa nhập các mặt hàng.")
                Exit Sub
            End If
            'Kiem tra them phieu hay cap nhap phieu
            If objPhieu Is Nothing Then
                If Not InsertDPNX() Then
                    Exit Sub
                End If
            Else
                If Not UpdateDPNX() Then
                    Exit Sub
                End If
            End If
            Dim btn As Button = CType(sender, Button)
            'Neu la cap nhat va close
            If btn Is btnCapNhat Then
                If fViewPhieuNX IsNot Nothing Then
                    fViewPhieuNX.RefreshForm()
                End If
            Else 'Neu la cap nhat va create new
                objPhieu = Nothing
                Init()
            End If
        Catch ex As Exception
            ShowMessages(ex.ToString())
        End Try
    End Sub

    Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        If fViewPhieuNX IsNot Nothing Then
            fViewPhieuNX.RefreshForm()
        End If
        Me.Close()
    End Sub

    Private Sub btnThemMH_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If cmbLoaiMH.SelectedIndex < 0 Then
            ShowMessages("Phải chọn Loại Mặt Hàng trước mới có thể thêm mặt hàng")
            Exit Sub
        End If
        If cmbLK.SelectedIndex < 0 Then
            ShowMessages("Phải chọn nhập vào Loại Kho trước mới có thể thêm mặt hàng")
            Exit Sub
        End If

        Dim objDT As CDoiTuong = CType(cmbLK.SelectedItem, CDoiTuong)
        Dim frm As New frmQuanLyLoHang(objDT.KH, CType(cmbLoaiMH.SelectedItem, CLoaiThuoc).MaLoaiThuoc)
        frm.fCallPhieuNX = Me
        frm.ShowDialog(Me)
    End Sub

    Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click
        If objPhieu IsNot Nothing Then
            If MessageBox.Show("Bạn có chắc là xóa phiếu này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                If objPhieu.Delete() > 0 Then
                    ShowMessages("Xong.")
                    If fViewPhieuNX IsNot Nothing Then
                        fViewPhieuNX.RefreshForm()
                    End If
                    Me.Close()
                End If
            End If
        End If
    End Sub
#End Region

#End Region

#Region "Functions"
    'Ham nay dung de hien thi huong dan cho nguoi su dung
    Public Function GetLabelNotify(Optional ByVal eNotify As enumLabelNotify = enumLabelNotify.None) As String
        Dim str As String = ""
        Select Case eNotify
            Case enumLabelNotify.DOITUONG, enumLabelNotify.MaColumn
                str = "Nhấn F1 hoặc đúp chuột để chọn"
            Case enumLabelNotify.HSDColumn
                str = "Nhập HSD là 4 ký tự số. Ví dụ: 1008 sẽ ra 10/08"
            Case enumLabelNotify.SLKHColumn
                str = "Bạn không có quyền sửa cột này"
            Case enumLabelNotify.SLTHColumn
                str = "Nhấn Enter để xác nhận số lượng của kế hoạch."
        End Select
        Return str
    End Function

    Public Sub InitPhieuNhap()
        enumNX = enumDOITUONG.TINHCHATNHAP
        Me.Text = "Phiếu nhập điều chỉnh số lượng sổ sách thừa"
        lblDVGN.Text = "Đơn vị giao"
        lblTCNX.Text = "Tính chất nhập"
        lblLK.Text = "Nhập vào Kho hàng"
        lblNguoiGN.Text = "&Người giao"
        lblNgayGN.Text = "Ngày nhập kho"
        Dim value As String
        value = BaseDB.ExecSql_DataValue("select KH from tblTCNX where L = 'N' and TEN = N'DCSS'")
        txtTCNX.ReadOnly = True
        txtTCNX.Text = CDoiTuongs.GetNameByMa(enumDOITUONG.TINHCHATNHAP, value)
        lblTCNX_ID.Text = value.ToString()
        txtDVGN.Text = ""
        lblDVGN_ID.Text = ""
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            Panel2.Height += 28
            lblSLTON.Visible = False
            lblKyQT.Visible = False
            cmbKyQT.Visible = False
            gridCTPhieu.AllowUserToAddRows = True
        ElseIf g_User.Ban_ID = enumPHANQUYEN.TCT Then
            gridCTPhieu.AllowUserToAddRows = False
            lblKyQT.Visible = True
            cmbKyQT.Visible = True

            Dim ds As DataSet = BaseDB.ExecSql_DataSet("select * from tblKyQT")
            cmbKyQT.DisplayMember = "tenkyqt"
            cmbKyQT.ValueMember = "id"
            cmbKyQT.DataSource = ds.Tables(0)

            'Disable cac control ko cho Tai chinh chinh sua
            cmbLoaiMH.Enabled = False
            cmbLK.Enabled = False
            dtNgay.Enabled = False

            txtSoPhieu.ReadOnly = True
            txtNgayPH.ReadOnly = True
            txtDVGN.ReadOnly = True
            txtTCNX.ReadOnly = True
            txtNguoiVP.ReadOnly = True
            txtNguoiGN.ReadOnly = True
            txtNgayGN.ReadOnly = True
            txtSoKien.ReadOnly = True
            txtTrLuong.ReadOnly = True
        End If
    End Sub

    Public Sub InitPhieuXuat()
        enumNX = enumDOITUONG.TINHCHATXUAT
        Me.Text = "Phiếu xuất điều chỉnh số lượng sổ sách thiếu"
        lblDVGN.Text = "Đơn vị nhận"
        lblTCNX.Text = "Tính chất xuất"
        lblLK.Text = "Xuất từ Kho hàng"
        lblNguoiGN.Text = "&Người nhận"
        lblNgayGN.Text = "Ngày nhận hàng"
        Dim value As String
        value = BaseDB.ExecSql_DataValue("select KH from tblTCNX where L = 'X' and TEN = N'DCSS'")
        txtTCNX.ReadOnly = True
        txtTCNX.Text = CDoiTuongs.GetNameByMa(enumDOITUONG.TINHCHATXUAT, value)
        lblTCNX_ID.Text = value.ToString()
        txtDVGN.Text = ""
        lblDVGN_ID.Text = ""
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            gridCTPhieu.AllowUserToAddRows = True
            lblKyQT.Visible = False
            cmbKyQT.Visible = False
        ElseIf g_User.Ban_ID = enumPHANQUYEN.TCT Then
            gridCTPhieu.AllowUserToAddRows = False
            lblKyQT.Visible = True
            cmbKyQT.Visible = True

            Dim ds As DataSet = BaseDB.ExecSql_DataSet("select * from tblKyQT")
            cmbKyQT.DisplayMember = "tenkyqt"
            cmbKyQT.ValueMember = "id"
            cmbKyQT.DataSource = ds.Tables(0)

            'Disable cac control ko cho Tai chinh chinh sua
            cmbLoaiMH.Enabled = False
            cmbLK.Enabled = False
            dtNgay.Enabled = False

            txtSoPhieu.ReadOnly = True
            txtNgayPH.ReadOnly = True
            txtDVGN.ReadOnly = True
            txtTCNX.ReadOnly = True
            txtNguoiVP.ReadOnly = True
            txtNguoiGN.ReadOnly = True
            txtNgayGN.ReadOnly = True
            txtSoKien.ReadOnly = True
            txtTrLuong.ReadOnly = True
        End If
    End Sub

    Public Sub Init()
        If objPhieu IsNot Nothing Then
            If objPhieu.NX = "N" Then
                InitPhieuNhap()
            Else
                InitPhieuXuat()
            End If
            With objPhieu
                objLoaiMH = CLoaiThuocs.GetLoaiThuocByMa(.LOAIMH)
                cmbLoaiMH.SelectedValue = .LOAIMH

                txtSoPhieu.Text = .SOPHIEU
                If .NGAYPH = DateNull() Then
                    txtNgayPH.Text = ""
                Else
                    txtNgayPH.Text = Format(.NGAYPH, FormatDateStyle())
                End If

                lblDVGN_ID.Text = .DVGN
                txtDVGN.Text = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.DONVI, .DVGN).Ten
                lblTCNX_ID.Text = .TCNX
                txtTCNX.Text = CDoiTuongs.GetDoiTuongByMa(enumNX, .TCNX).Ten

                lblLK_ID.Text = .LK
                cmbLK.SelectedValue = .LK

                If .NGAYGN = DateNull() Then
                    txtNgayGN.Text = ""
                Else
                    txtNgayGN.Text = Format(.NGAYGN, FormatDateStyle())
                End If

                txtNguoiVP.Text = .NGUOIVP
                dtNgay.Value = .NGAY
                txtSoKH.Text = .SOKH.ToString(FormatQuantityStyle())
                txtSoKien.Text = .SOKIEN.ToString(FormatQuantityStyle())
                txtTrLuong.Text = .TRLUONG.ToString(FormatQuantityStyle())
                Try
                    txtTGiaTri.Text = .TGIATRI.ToString(FormatMoneyStyle())
                Catch ex As Exception
                    txtTGiaTri.Text = "0"
                End Try

                If .BCTH = enumBCTH.KH Then
                    lblBCTH.Text = "Chưa xác nhận (KH)"
                ElseIf .BCTH = enumBCTH.TC Then
                    lblBCTH.Text = "Đã xác nhận (TC)"
                End If

                Try
                    cmbKyQT.SelectedValue = .KYQT
                Catch ex As Exception
                    cmbKyQT.SelectedValue = 1
                End Try
            End With
        Else
            btnXoa.Enabled = False
            cmbLoaiMH.SelectedIndex = 4
            txtSoPhieu.Text = ""
            lblDVGN_ID.Text = ""
            txtDVGN.Text = ""
            txtNgayPH.Text = ""
            cmbLK.SelectedIndex = 0
            txtNguoiGN.Text = ""
            txtNgayGN.Text = ""
            txtNguoiVP.Text = g_User.FullName
            dtNgay.Text = ""
            txtSoKH.Text = ""
            txtSoKien.Text = ""
            txtTrLuong.Text = ""
            txtTGiaTri.Text = ""
            lblBCTH.Text = "Chưa xác nhận (KH)"
            cmbKyQT.SelectedValue = 1
            If enumNX = enumDOITUONG.TINHCHATNHAP Then
                InitPhieuNhap()
            Else
                InitPhieuXuat()
            End If
            lblSLTON.Text = ""
        End If
        FormatGridStyleCTPhieuNhap()
        ControlSetFocus(cmbLoaiMH)
    End Sub

    'Ham nay dung de hien thi danh muc DVGN va TCNX de chon gia tri
    Public Sub ShowFormDoiTuong(ByVal loai As enumDOITUONG, ByVal value As String)
        Dim frm As New frmDMDoiTuong
        Select Case loai
            Case enumDOITUONG.DONVI
                frm.Text = "Chọn đơn vị"
            Case enumDOITUONG.TINHCHATNHAP
                frm.Text = "Chọn Tính chất nhập"
            Case enumDOITUONG.TINHCHATXUAT
                frm.Text = "Chọn Tính chất xuất"
        End Select
        frm.bCallForm = True
        frm.eDoiTuong = loai
        frm.sFind = value
        frm.ShowDialog()
        If frm.selectedDT IsNot Nothing Then
            Select Case loai
                Case enumDOITUONG.DONVI
                    lblDVGN_ID.Text = frm.selectedDT.KH
                    txtDVGN.Text = frm.selectedDT.Ten
                Case enumDOITUONG.TINHCHATNHAP, enumDOITUONG.TINHCHATXUAT
                    lblTCNX_ID.Text = frm.selectedDT.KH
                    txtTCNX.Text = frm.selectedDT.Ten
            End Select
        Else
            Select Case loai
                Case enumDOITUONG.DONVI
                    lblDVGN_ID.Text = ""
                    txtDVGN.Text = ""
                Case enumDOITUONG.TINHCHATNHAP, enumDOITUONG.TINHCHATXUAT
                    lblTCNX_ID.Text = ""
                    txtTCNX.Text = ""
            End Select
        End If
    End Sub

    Public Function PopulatePhieuInfo() As Boolean
        Dim str(2) As String
        Dim len As Integer = 0
        With objPhieu
            .NX = LocNhapXuat(enumNX)
            If cmbLoaiMH.SelectedIndex < 0 Then
                ShowMessages("Chưa chọn loại mặt hàng")
                If cmbLoaiMH.CanFocus Then
                    cmbLoaiMH.Focus()
                End If
                Return False
            Else
                .LOAIMH = CType(cmbLoaiMH.SelectedItem, CLoaiThuoc).MaLoaiThuoc
            End If

            If txtSoPhieu.Text = "" Then
                ShowMessages("Số phiếu chưa nhập.")
                If txtSoPhieu.CanFocus Then
                    txtSoPhieu.Focus()
                End If
                Return False
            Else
                .SOPHIEU = txtSoPhieu.Text
            End If
            'Kiểm tra độ dài phiếu hợp lệ
            len = .ColumnLength("sophieu")
            If len < .SOPHIEU.Length Then
                ShowMessages("Chiều dài ký tự Số phiếu vượt quá " + len.ToString())
                txtSoPhieu.Focus()
                Return False
            End If

            Try
                .NGAYPH = ConvertStringTypeToDateType(txtNgayPH.Text)
            Catch ex As Exception
                .NGAYPH = CDate("1/1/2001")
            End Try
            .DVGN = lblDVGN_ID.Text
            'Chi kiem tra TCNX doi voi truong hop lap phieu nhap
            'Phieu xuat khong can TCNX
            .TCNX = lblTCNX_ID.Text
            .LK = CType(cmbLK.SelectedItem, CDoiTuong).KH
            If .LK Is Nothing Then
                ShowError("Loại kho chưa chọn.")
                Return False
            End If
            .THEOLENH = ""
            .HOPDONG = Nothing
            .NGUOIGN = txtNguoiGN.Text
            len = .ColumnLength("nguoign")
            If len < .NGUOIGN.Length Then
                ShowMessages("Chiều dài ký tự của Người GN vượt quá " + len.ToString())
                txtNguoiGN.Focus()
                Return False
            End If
            .GGT = ""
            .NGAYKGGT = DateNull()
            Try
                .NGAYGN = ConvertStringTypeToDateType(txtNgayGN.Text)
            Catch ex As Exception
                .NGAYGN = DateNull()
            End Try

            .NGUOIVP = txtNguoiVP.Text
            len = .ColumnLength("nguoivp")
            If len < .NGUOIVP.Length Then
                ShowMessages("Chiều dài ký tự của Người VP vượt quá " + len.ToString())
                txtNguoiVP.Focus()
                Return False
            End If
            .NGAY = Me.dtNgay.Value.Date
            Try
                .SOKH = GetRowCount()
            Catch ex As Exception
                .SOKH = 0
            End Try
            Try
                .SOKIEN = CUInt(txtSoKien.Text)
            Catch ex As Exception
                .SOKIEN = Nothing
            End Try
            Try
                .TRLUONG = Double.Parse(txtTrLuong.Text)
            Catch ex As Exception
                .TRLUONG = Nothing
            End Try
            Try
                .TGIATRI = CType(txtTGiaTri.Text, Double)
            Catch ex As Exception
                .TGIATRI = 0
            End Try
            .HTTT = Nothing
            If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
                .KYQT = 1
                .BCTH = 1
            ElseIf g_User.Ban_ID = enumPHANQUYEN.TCT Then
                .BCTH = 2
                .KYQT = cmbKyQT.SelectedValue
            End If
            If txtNgayPH.Text <> "  /  /" Then
                If .NGAYPH < .NGAY Then
                    ShowMessages("Thời hạn phiếu phải > Ngày lập phiếu")
                    If txtNgayPH.CanFocus Then
                        txtNgayPH.Focus()
                    End If
                    Return False
                End If
            End If
        End With
        Return True
    End Function

    Public Sub FormatGridStyleCTPhieuNhap()
        sdaSLNX = Nothing
        dsDataSet = Nothing
        Try
            sdaSLNX = g_objConnFactory.CreateAdapter
            CSLNXs.CreateDataSetSLNX(sdaSLNX, dsDataSet, objPhieu.DPNX_ID)
        Catch ex As Exception
            CSLNXs.CreateDataSetSLNX(sdaSLNX, dsDataSet, Nothing)
        End Try
        Dim dv As DataView
        dv = dsDataSet.Tables(0).DefaultView
        gridCTPhieu.DataSource = dv

        With gridCTPhieu
            'Frozen
            'Column Combobox makho da set Frozen = True trong luc tao
            .Columns.Item("kho").Frozen = True
            .Columns.Item("ten").Frozen = True
            .Columns.Item("lo").Frozen = True

            .Columns.Item("ma").HeaderText = "Mã"
            .Columns.Item("code").HeaderText = "Code"
            .Columns.Item("kho").HeaderText = "Kho"
            .Columns.Item("ten").HeaderText = "Tên hàng"
            .Columns.Item("dvt").HeaderText = "Đvt"
            .Columns.Item("lo").HeaderText = "Lô hàng"
            .Columns.Item("hansd").HeaderText = "Hạn SD"
            .Columns.Item("h").HeaderText = "CCL"
            .Columns.Item("ghichu").HeaderText = "Ghi chú"
            With .Columns.Item("slkh")
                .HeaderText = "SL Kế hoạch"
                .DefaultCellStyle.Format = FormatQuantityStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .DefaultCellStyle.BackColor = Color.LightGreen
            End With
            With .Columns.Item("slth")
                .HeaderText = "SL Thực hiện"
                .DefaultCellStyle.Format = FormatQuantityStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .DefaultCellStyle.BackColor = Color.LightGreen
            End With
            With .Columns.Item("gle")
                .HeaderText = "Đơn giá"
                .DefaultCellStyle.Format = FormatMoneyStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With
            With .Columns.Item("thanhtien")
                .HeaderText = "Thành tiền"
                .DefaultCellStyle.Format = FormatMoneyStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With

            .Columns.Item("mathang_id").Visible = False
            .Columns.Item("slnx_id").Visible = False
            .Columns.Item("kho").Visible = False
            .Columns.Item("ma").Visible = False
            .Columns.Item("code").Visible = False
            .Columns.Item("lk").Visible = False
            .Columns.Item("dpnx_id").Visible = False
            .Columns.Item("ngtton").Visible = False
            .Columns.Item("slss11").Visible = False
            .Columns.Item("slkk11").Visible = False
            .Columns.Item("sltonkh").Visible = False
            .Columns.Item("sltonth").Visible = False
            .Columns.Item("sltonss").Visible = False

            .Columns.Item("kho").ReadOnly = True
            .Columns.Item("ten").ReadOnly = True
            .Columns.Item("dvt").ReadOnly = True
            .Columns.Item("lo").ReadOnly = True
            .Columns.Item("hansd").ReadOnly = True
            .Columns.Item("h").ReadOnly = True
            .Columns.Item("gle").ReadOnly = True
            .Columns.Item("thanhtien").ReadOnly = True
            'Kiem tra phan quyen va chi cho nhap column phu hop
            If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
                .Columns.Item("makho").Visible = True
                .Columns.Item("kho").Visible = False
                .Columns.Item("slth").Visible = False
                'Add combobox KHO
                AddComboBoxColumns_Kho()
            ElseIf g_User.Ban_ID = enumPHANQUYEN.TCT Then
                .Columns.Item("makho").Visible = False
                .Columns.Item("kho").Visible = True
                .Columns.Item("slkh").ReadOnly = True
            End If

            RowCount = GetRowCount()
            For count As Integer = 0 To RowCount - 1
                gridCTPhieu.Rows(count).HeaderCell.Value = (count + 1).ToString
            Next
        End With
    End Sub

    'Kiem tra xem mat hang can chon da co trong grid chua
    Private Function isNewMatHang(ByVal mathang_id As Integer) As Boolean
        For Each dr As DataGridViewRow In gridCTPhieu.Rows
            If dr.Cells("mathang_id").Value IsNot DBNull.Value Then
                If CInt(dr.Cells("mathang_id").Value) = mathang_id Then
                    Return False
                End If
            End If
        Next
        Return True
    End Function

    Public Sub AddMatHang(ByVal objMatHang As CMatHang, ByVal slkh As Double, ByVal count As Integer)
        If isNewMatHang(objMatHang.MatHang_ID) Then
            'Dim objMatHang As CMatHang = CMatHangs.GetMatHangByMa(mathang_id)
            Dim dt As DataTable = dsDataSet.Tables(0)
            Dim NewRow As DataRow
            NewRow = dt.NewRow
            NewRow("makho") = objMatHang.Kho
            NewRow("kho") = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.KHO, objMatHang.Kho).Ten
            NewRow("mathang_id") = objMatHang.MatHang_ID
            NewRow("ma") = objMatHang.Ma
            NewRow("code") = objMatHang.Code
            NewRow("ten") = objMatHang.Ten
            NewRow("dvt") = objMatHang.DVT
            NewRow("lo") = objMatHang.Lo
            NewRow("hansd") = objMatHang.HanSD
            NewRow("lk") = objMatHang.LK
            NewRow("h") = objMatHang.H
            NewRow("slnx_id") = DBNull.Value
            '***Phai doi ra dung format truoc khi tinh thanh tien
            If slkh > 0 Then
                slkh = CType(slkh.ToString(FormatMoneyStyle()), Double)
            End If
            NewRow("slkh") = slkh
            NewRow("slth") = slkh
            NewRow("gle") = objMatHang.Gle
            'Tinh thanh tien sau khi format xong
            Dim thanhtien As Double = slkh * objMatHang.Gle
            NewRow("thanhtien") = CType(thanhtien, Long)
            NewRow("ghichu") = ""
            Try
                NewRow("dpnx_id") = objPhieu.DPNX_ID
            Catch ex As Exception
                NewRow("dpnx_id") = DBNull.Value
            End Try
            NewRow("sltonkh") = objMatHang.SLTonKH
            NewRow("sltonth") = objMatHang.SLTonTH
            NewRow("sltonss") = objMatHang.SLTonSS
            If count = 1 Then
                Dim RowIndex As Integer = gridCTPhieu.SelectedCells(0).RowIndex
                gridCTPhieu.Rows.RemoveAt(RowIndex) 'Xoa cai dong tai vi tri can insert
                dt.AcceptChanges()
                dt.Rows.InsertAt(NewRow, RowIndex) 'Add vao vi tri insert
                dt.AcceptChanges()
                gridCTPhieu.Rows(RowIndex).HeaderCell.Value = (RowIndex + 1).ToString 'Hien thi lai STT o dau moi dong
                gridCTPhieu.Refresh() 'Refresh lai
            Else
                dt.Rows.InsertAt(NewRow, dt.Rows.Count)
                dt.AcceptChanges()
                gridCTPhieu.Rows(dt.Rows.Count - 1).HeaderCell.Value = (dt.Rows.Count).ToString
                gridCTPhieu.Refresh()
            End If
        End If
        ShowSoKH_TGiaTri()
    End Sub

    'Ham nay dung de hien thi tong gia tri phieu va so khoan cua phieu
    Public Sub ShowSoKH_TGiaTri()
        Dim sum As Double = 0
        RowCount = GetRowCount()
        For i As Integer = 0 To RowCount - 1
            gridCTPhieu.Rows(i).HeaderCell.Value = (i + 1).ToString
            If gridCTPhieu.Rows(i).Cells("thanhtien").Value IsNot DBNull.Value Then
                sum += gridCTPhieu.Rows(i).Cells("thanhtien").Value
            End If
        Next
        txtSoKH.Text = CStr(RowCount)
        txtTGiaTri.Text = Format(sum, FormatMoneyStyle())
    End Sub

    'Ham nay dung de thay the MaKho textbox column thanh combobox column
    Private Sub AddComboBoxColumns_Kho()
        Dim comboboxColumn As New DataGridViewComboBoxColumn()
        With comboboxColumn
            .Name = "makho"
            .DataPropertyName = "makho"
            .HeaderText = "Kho"
            .Frozen = True
            .FlatStyle = FlatStyle.Flat
            .DropDownWidth = 150 'gridCTPhieu.Columns("kho").Width
            .Width = gridCTPhieu.Columns("makho").Width
            .DataSource = CDoiTuongs.GetDoiTuongList(enumDOITUONG.KHO)
            .ValueMember = "KH"
            .DisplayMember = "Ten"
        End With
        Try
            gridCTPhieu.Columns.Remove("makho")
            gridCTPhieu.Columns.Insert(0, comboboxColumn)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    'Ham nay dung de dem so row co trong grid
    Public Function GetRowCount() As UInteger
        Dim mRowCount As UInteger = 0
        Try
            If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
                mRowCount = gridCTPhieu.RowCount - 1
            ElseIf g_User.Ban_ID = enumPHANQUYEN.TCT Then
                mRowCount = gridCTPhieu.RowCount
            End If
        Catch ex As Exception
            mRowCount = 0
        End Try
        Return mRowCount
    End Function

    'Ham nay dung de luu row trong grid thanh doi tuong CMatHang
    Private Function GetMatHang(ByVal dr As DataGridViewRow, ByRef obj As CMatHang) As Boolean
        obj = New CMatHang

        obj.Kho = dr.Cells("makho").Value

        Try
            obj.Ma = dr.Cells("ma").Value
        Catch ex As Exception
            ShowError("Mã mặt hàng chưa chọn")
            dr.Cells("ten").Selected = True
            Return False
        End Try

        obj.Ten = dr.Cells("ten").Value
        obj.Code = dr.Cells("code").Value

        Try
            obj.Lo = dr.Cells("lo").Value
        Catch ex As Exception
            obj.HanSD = Nothing
        End Try

        Try
            obj.HanSD = dr.Cells("hansd").Value
        Catch ex As Exception
            obj.HanSD = Nothing
        End Try

        Dim objLK As CDoiTuong = cmbLK.SelectedItem
        obj.LK = objLK.KH

        Try
            obj.H = dr.Cells("h").Value
        Catch ex As Exception
            obj.H = Nothing
        End Try

        obj.NgTTon = Now.ToShortDateString()

        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            Try
                obj.SLTonKH = dr.Cells("slkh").Value
                If obj.SLTonKH = 0 Then
                    ShowError("SLKH chưa nhập.")
                    dr.Cells("slkh").Selected = True
                    Return False
                End If
            Catch ex As Exception
                ShowError("SLKH chưa nhập.")
                dr.Cells("slkh").Selected = True
                Return False
            End Try
        ElseIf g_User.Ban_ID = enumPHANQUYEN.TCT Then
            Try
                obj.SLTonTH = dr.Cells("slth").Value
                If obj.SLTonTH = 0 Then
                    ShowError("SLTH chưa nhập.")
                    dr.Cells("slth").Selected = True
                    Return False
                End If
            Catch ex As Exception
                ShowError("SLTH chưa nhập.")
                dr.Cells("slth").Selected = True
                Return False
            End Try
        End If

        obj.DVT = dr.Cells("dvt").Value
        Try
            obj.Gle = dr.Cells("gle").Value
        Catch ex As Exception
            ShowError("Đơn giá chưa nhập")
            dr.Cells("gle").Selected = True
            Return False
        End Try
        Return True
    End Function

    Public Function CompareValue(ByVal value1 As Object, ByVal value2 As Object) As Boolean
        If value1 Is DBNull.Value And value2 Is DBNull.Value Then
            Return True
        ElseIf value1 IsNot DBNull.Value And value2 IsNot DBNull.Value Then
            If value1 = value2 Then
                Return True
            Else
                Return False
            End If
        End If
        Return False
    End Function

    Public Function InsertDPNX() As Boolean
        Dim objMH(RowCount - 1) As CMatHang
        Dim dvr As DataGridViewRow
        objPhieu = New CPhieuNX()
        'Kiem tra va Luu thong tin DPNX
        If PopulatePhieuInfo() Then
            'Kiem tra va luu thong tin SLNX
            For i As Integer = 0 To RowCount - 1
                dvr = gridCTPhieu.Rows(i)
                If Not GetMatHang(dvr, objMH(i)) Then
                    objPhieu = Nothing 'Reset lai objPhieu
                    Return False
                End If
            Next
            'Kiem tra va Them phieu nhap xuat neu dc
            If objPhieu.Insert() > 0 Then
                For Each dr As DataRow In dsDataSet.Tables(0).Rows
                    dr("dpnx_id") = objPhieu.DPNX_ID
                Next
                If enumNX = enumDOITUONG.TINHCHATNHAP Then
                    For i As Integer = 0 To RowCount - 1
                        objMH(i).MatHang_ID = gridCTPhieu.Rows(i).Cells("mathang_id").Value
                        objMH(i).AddSLTONSS(ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value))
                    Next
                ElseIf enumNX = enumDOITUONG.TINHCHATXUAT Then
                    For i As Integer = 0 To RowCount - 1
                        objMH(i).MatHang_ID = gridCTPhieu.Rows(i).Cells("mathang_id").Value
                        objMH(i).SubstractSLTONSS(ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value))
                    Next
                End If

                Dim objSLNX As CSLNX
                For i As Integer = 0 To RowCount - 1
                    Dim dr As DataGridViewRow = gridCTPhieu.Rows(i)
                    objSLNX = New CSLNX()
                    objSLNX.DPNX_ID = objPhieu.DPNX_ID
                    objSLNX.MATHANG_ID = dr.Cells("mathang_id").Value
                    objSLNX.SLKH = ChuanHoaSo(dr.Cells("slkh").Value)
                    objSLNX.SLTH = ChuanHoaSo(dr.Cells("slth").Value)
                    objSLNX.THANHTIEN = ChuanHoaSo(dr.Cells("thanhtien").Value)
                    Try
                        objSLNX.GhiChu = dr.Cells("ghichu").Value
                    Catch ex As Exception
                        objSLNX.GhiChu = Nothing
                    End Try
                    'Insert SLNX
                    dr.Cells("slnx_id").Value = objSLNX.Insert()
                Next
                ShowSoKH_TGiaTri()
                objPhieu.SOKH = txtSoKH.Text
                objPhieu.TGIATRI = txtTGiaTri.Text
                objPhieu.Update()

                '==========================
                'Write log
                CLogs.WriteLog_PhieuNX(enumAction.ThemMoi, objPhieu)

                ShowMessages("Đã thêm phiếu mới xong.")
                Return True
            End If
        End If
        objPhieu = Nothing
        Return False
    End Function

    Public Function UpdateDPNX() As Boolean
        Dim objMH(RowCount - 1) As CMatHang
        Dim dvr As DataGridViewRow
        If PopulatePhieuInfo() Then
            'Kiem tra va luu thong tin SLNX
            For i As Integer = 0 To RowCount - 1
                dvr = gridCTPhieu.Rows(i)
                If Not GetMatHang(dvr, objMH(i)) Then
                    Return False
                End If
            Next
            'Kiem tra va Cap nhat phieu nhap xuat neu dc
            If objPhieu.Update() > 0 Then
                'Update lai slton cua cac mathang <=> xoa het du lieu trong bang SLNX
                CMatHangs.ResetSLTONMatHangByDPNX_DCSS(objPhieu.DPNX_ID)
                'Xoa het cac SLNX trong tblSLNX theo DPNX_ID
                CSLNXs.DeleteSLNXByDPNX_ID(objPhieu.DPNX_ID)
                'Xet truong hop la phieu nhap neu co mat hang moi them vao
                If enumNX = enumDOITUONG.TINHCHATNHAP Then
                    For i As Integer = 0 To RowCount - 1
                        objMH(i).MatHang_ID = gridCTPhieu.Rows(i).Cells("mathang_id").Value
                        objMH(i).AddSLTONSS(ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value))
                    Next
                ElseIf enumNX = enumDOITUONG.TINHCHATXUAT Then
                    For i As Integer = 0 To RowCount - 1
                        objMH(i).MatHang_ID = gridCTPhieu.Rows(i).Cells("mathang_id").Value
                        objMH(i).SubstractSLTONSS(ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value))
                    Next
                End If
                'Them lai cac SLNX vao tblSLNX
                Dim objSLNX As CSLNX
                For i As Integer = 0 To RowCount - 1
                    Dim dr As DataGridViewRow = gridCTPhieu.Rows(i)
                    objSLNX = New CSLNX()
                    objSLNX.DPNX_ID = objPhieu.DPNX_ID
                    objSLNX.MATHANG_ID = dr.Cells("mathang_id").Value
                    objSLNX.SLKH = ChuanHoaSo(dr.Cells("slkh").Value)
                    objSLNX.SLTH = ChuanHoaSo(dr.Cells("slth").Value)
                    objSLNX.THANHTIEN = ChuanHoaSo(dr.Cells("thanhtien").Value)
                    Try
                        objSLNX.GhiChu = dr.Cells("ghichu").Value
                    Catch ex As Exception
                        objSLNX.GhiChu = Nothing
                    End Try
                    dr.Cells("slnx_id").Value = objSLNX.Insert()
                Next
                ShowSoKH_TGiaTri()
                objPhieu.SOKH = txtSoKH.Text
                objPhieu.TGIATRI = txtTGiaTri.Text
                objPhieu.Update()

                '==========================
                'Write log
                CLogs.WriteLog_PhieuNX(enumAction.Sua, objPhieu)

                ShowMessages("Đã cập nhật xong")
                Return True
            End If
        End If
        Return False
    End Function
#End Region

    Private Sub btnInPhieu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInPhieu.Click
        If objPhieu Is Nothing Then
            Exit Sub
        End If
        Dim objSelectedPhieu As CPhieuNX = CPhieuNXs.GetPhieuByMa(objPhieu.DPNX_ID)
        Dim strSql As String
        strSql = "select * from viewNhapXuat where DPNX_ID = " & objSelectedPhieu.DPNX_ID.ToString()
        Dim ds As DataSet
        ds = BaseDB.ExecSql_DataSet(strSql)

        Dim ten_dvgn, ten_lk, ten_tcnx As String
        ten_dvgn = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.DONVI, objSelectedPhieu.DVGN).Ten
        ten_lk = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.LOAIKHO, objSelectedPhieu.LK).Ten
        Dim nnreport As New rptPhieuNhapKho
        nnreport.SetDataSource(ds.Tables(0))
        nnreport.SetParameterValue("ten_dvgn", ten_dvgn)
        nnreport.SetParameterValue("ten_lk", ten_lk)
        nnreport.SetParameterValue("tien_chu", DoiSoRaChu(objSelectedPhieu.TGIATRI))
        If (objSelectedPhieu.NX = "N") Then
            ten_tcnx = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATNHAP, objSelectedPhieu.TCNX).Ten
            nnreport.SetParameterValue("loai_phieu", "N")
        Else
            ten_tcnx = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATXUAT, objSelectedPhieu.TCNX).Ten
            nnreport.SetParameterValue("loai_phieu", "X")
        End If
        nnreport.SetParameterValue("ten_tcnx", ten_tcnx)
        Dim frm As New frmReportViewer(nnreport)
        frm.ShowDialog()
    End Sub

    'Private Sub chkTCXacNhan_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    If g_User.Ban_ID = enumPHANQUYEN.TCT Then
    '        If chkTCXacNhan.Checked Then
    '            For i As Integer = 0 To RowCount - 1
    '                gridCTPhieu.Rows(i).Cells("slth").Value = gridCTPhieu.Rows(i).Cells("slkh").Value
    '            Next
    '            lblBCTH.Text = "Đã xác nhận (TC)"
    '        Else
    '            For i As Integer = 0 To RowCount - 1
    '                gridCTPhieu.Rows(i).Cells("slth").Value = DBNull.Value
    '            Next
    '            lblBCTH.Text = "Chưa xác nhận (KH)"
    '        End If
    '    End If
    'End Sub
End Class